import React, { useState, useRef, useEffect } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import { connect } from 'umi';
import { queryComputerList,saveOrUpdateCredential,deleteCredential,memberSubsidyBpm,getComputerSubsidyEndDate} from '../service';
import moment from 'moment';
import {PlusOutlined} from '@ant-design/icons';
import {Popconfirm,Divider,Button,message} from 'antd';
import HousingAddForm from '../components/HousingAddForm';
import { applyMannerList, BPMStatusEnum } from '@/utils/constant'

const TableList = () => {
  const actionRef = useRef();
  const [visible, setVisible] = useState(null);
  const [record,setRecord] = useState(null);
  const [loading,setLoading] = useState(false);
  const [flag,setFlag] = useState(true);

  const columns = [
    {
      title: '工号',
      dataIndex: 'code',
    },
    {
      title: '姓名',
      dataIndex: 'name',
    },
    {
      title: '申请方式',
      dataIndex: 'applyMode',
      render: (text) => {
        return applyMannerList.find((item) => item.value === text)?.label;
      },
    },
    {
      title: '申请时间',
      dataIndex: 'applyDate',
      hideInSearch: true,
      render: (text) => {
        return text !== '-' ? moment(text).format('YYYY-MM-DD') : '';
      },
    },
    {
      title: '申请总金额',
      dataIndex: 'sum',
      render: (text,record) => {
        return record.monthlyAmount * parseInt(record.duration) + '元';
      },
    },
    {
      title: '每月金额',
      dataIndex: 'monthlyAmount',
      render: (text) => {
        return text + '元';
      },
    },
    {
      title: '补贴开始时间',
      dataIndex: 'startDate',
      hideInSearch: true,
      render: (text) => {
        return text !== '-' ? moment(text).format('YYYY-MM') : '';
      },
    },
    {
      title: '补贴结束时间',
      dataIndex: 'endDate',
      hideInSearch: true,
      render: (text) => {
        return text !== '-' ? moment(text).format('YYYY-MM') : '';
      },
    },
    {
      title: '审批状态',
      dataIndex: 'approveStatus',
      hideInSearch: true,
      valueEnum: BPMStatusEnum,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      align:'center',
      width: '15%',
      render: (item, record) => (
        <>
          {
            (record.approveStatus === 0) && <>
              <a onClick={() => addOrEditComputer(record)}>修改</a>
              <Divider type="vertical"/>
              <Popconfirm title={`是否确认删除?`} onConfirm={() => delComputer(record.id)} okText="是" cancelText="否">
                <a>删除</a>
              </Popconfirm>
              <Divider type="vertical"/>
              <Popconfirm title={`是否确认发起?`} onConfirm={() => sendBpm(record.id)} okText="是" cancelText="否">
                <a>发起审批</a>
              </Popconfirm>
            </>
          }
          {(record.approveStatus !== 0 && record.bpmUrl) && <><a onClick={() => window.open(record.bpmUrl)}>审批详情</a></>}
        </>
      ),
    },
  ];

  const getEndDate = () => {
    getComputerSubsidyEndDate(4).then(res =>{
      //结束日期大于或等于当前月份相同才允许新增
      setFlag(res ? moment(res).format("YYYY-MM") <= moment().format("YYYY-MM") ? false : true : false);
    });
  };

  useEffect(() => {
    //获取最晚的结束日期
    getEndDate();
  }, []);

  const addOrEditComputer = (record) => {
    if(record){
      setRecord(record);
    }
    setVisible(true);
  };

  const delComputer = (id) => {
    deleteCredential(id).then(res => {
      if (res.flag) {
        getEndDate();
        message.success(`删除成功!`);
        actionRef.current.reload();
      } else {
        message.error(res.error);
      }
    });
  };

  const sendBpm = (id) => {
    memberSubsidyBpm(id).then(res => {
      if (res.flag){
        actionRef.current.reload();
        message.success(`发起成功!`);
        window.open(res.data);
      }else {
        message.error(res.error);
      }
    });
  };

  const handleCancel = () => {
    setVisible(false);
    setRecord(null);
  };

  const handleSubmit = (values) => {
    setLoading(true);
    saveOrUpdateCredential(values).then((res) => {
      if (res.flag) {
        handleCancel();
        getEndDate();
        message.success('操作成功！');
        actionRef.current.reload();
      } else {
        message.error(res.error);
      }
      setLoading(false);
    })
  };

  return (
    <PageHeaderWrapper>
      <ProTable
        actionRef={actionRef}
        rowKey="id"
        search={false}
        request={(params) => queryComputerList(params,4)}
        columns={columns}
        toolBarRender={(action, {selectedRows}) => [
          <Button type="primary" disabled={flag} onClick={() => addOrEditComputer(null)}><PlusOutlined/>新增</Button>
        ]}
      />
      <HousingAddForm
        loading={loading}
        visible={visible}
        record={record}
        type={4}
        applyMode={2}
        onCancel={handleCancel}
        onSubmit={handleSubmit}
      />
    </PageHeaderWrapper>
  )
};

export default connect(() => ({
}))(TableList)
